package test.hxy.mongoSchoolSimple.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import test.hxy.mongoSchoolSimple.DTO.Response;
import test.hxy.mongoSchoolSimple.model.Campus;
import test.hxy.mongoSchoolSimple.service.CampusService;

import java.util.List;

@RestController
@RequestMapping("/campus")
public class CampusController extends BaseController {
	@Autowired
	CampusService campusService;

	@GetMapping("/findAll")
	@ResponseBody
	public Response<List<Campus>> findAll(){
		List<Campus> campuses = campusService.findAll();
		if (campuses.size() == 0) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(campuses);
		}
	}

	@GetMapping("/findByCampusNameContains")
	@ResponseBody
	public Response<List<Campus>> findByCampusNameContains(@RequestParam String campusName){
		List<Campus> campuses = campusService.findByCampusNameContains(campusName);
		if (campuses.size() == 0) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(campuses);
		}
	}

	@GetMapping("/findByCampusIdEquals")
	@ResponseBody
	public Response<Campus> findByCampusIdEquals(@RequestParam String campusId){
		Campus campuse = campusService.findByCampusIdEquals(campusId);
		if (campuse == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(campuse);
		}
	}

	@PostMapping("/insert")
	@ResponseBody
	public Response<Campus> insertCampus(@RequestBody Campus campus) {
		Campus temp = campusService.insertCampus(campus);
		if (temp == null) {
			return getFailResult(400, "ID已存在!");
		} else {
			return getSuccessResult(temp);
		}
	}

	@GetMapping("/delete")
	@ResponseBody
	public Response<Campus> delete(@RequestParam String campusId){
		Campus campuse = campusService.delete(campusId);
		if (campuse == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(campuse);
		}
	}

	@PostMapping("/update")
	@ResponseBody
	public Response<String> update(@RequestBody Campus campus) {
		if (campusService.delete(campus.getCampusId()) != null) {
			campusService.insertCampus(campus);
			return getSuccessResult("Success");
		} else {
			return getFailResult(404, "不存在该数据");
		}
	}

}
